package com.bank.utils;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class FdfsUtils {

    private static final Logger logger = LoggerFactory.getLogger(FdfsUtils.class);

    private FdfsUtils() {
    }

    /**
     * @param fastFileStorageClient fdfs提供的操作类对象
     * @param file                  要上传的文件对象
     * @return 文件在fdfs中的全路径
     * @throws FileNotFoundException
     */
    public static String uploadFile(FastFileStorageClient fastFileStorageClient, File file) throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream(file);
        StorePath storePath = fastFileStorageClient.uploadFile(fileInputStream, file.length(), FilenameUtils.getExtension(file.getName()), null);
        String fullPath = storePath.getFullPath();
        return fullPath;
    }

    public static String uploadFile(FastFileStorageClient fastFileStorageClient, InputStream inputStream, String filename, Long fileSize) {
        StorePath storePath = fastFileStorageClient.uploadFile(inputStream, fileSize, FilenameUtils.getExtension(filename), null);
        logger.info("storePath: {}", storePath.getFullPath());
        return storePath.getFullPath();
    }

    public static void deleteFile(FastFileStorageClient fastFileStorageClient, String url) {
        if (StringUtils.isEmpty(url)) {
            return;
        }
        logger.info("url: {}", url);
        try {
            StorePath storePath = StorePath.parseFromUrl(url);
            logger.info("storePath: {}", storePath.getFullPath());
            fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            logger.error(e.getMessage());
        }
    }
}
